package com.freak.wanandroid.model.login.login;

import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.freak.wanandroid.R;
import com.freak.wanandroid.base.fragment.BaseLifecycleFragment;
import com.freak.wanandroid.bean.LoginBean;
import com.freak.wanandroid.util.ToastUtil;
import com.freak.wanandroid.util.ToolUtils;

/**
 * Created by 74099 on 2018/8/29.
 */

public class LoginFragment extends BaseLifecycleFragment<LoginViewModel> implements View.OnClickListener {
    private EditText mEdtLoginUser, mEdtLoginPw;
    private TextView mTvLoginCommit, mTvForgetPw, mTvFindPw;

    public static LoginFragment newInstance() {
        LoginFragment fragment = new LoginFragment();
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_login;
    }

    @Override
    protected void initEventAndData(View view) {
        mEdtLoginUser = view.findViewById(R.id.edt_login_user);
        mEdtLoginPw = view.findViewById(R.id.edt_login_pw);
        mTvLoginCommit = view.findViewById(R.id.tv_login_commit);
        mTvForgetPw = view.findViewById(R.id.tv_forget_pw);
        mTvFindPw = view.findViewById(R.id.tv_find_pw);
        mTvLoginCommit.setOnClickListener(this);
        mTvForgetPw.setOnClickListener(this);
        mTvFindPw.setOnClickListener(this);
    }

    private String getUserName() {
        return mEdtLoginUser.getText().toString().trim();
    }

    private String getPassword() {
        return mEdtLoginPw.getText().toString().trim();
    }

    @Override
    protected void onResumeLoadData() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_find_pw:
                break;
            case R.id.tv_forget_pw:
                break;
            case R.id.tv_login_commit:
                if (ToolUtils.isNull(getUserName())) {
                    ToastUtil.showLong(getActivity(), "请输入账号");
                } else if (ToolUtils.isNull(getPassword())) {
                    ToastUtil.showShort(getActivity(), "请输入密码");
                } else {
                    mViewModel.doLogin(getUserName(), getPassword());
                }
                break;
            default:
                break;
        }
    }

    public void doLoginSuccess(LoginBean loginBean) {
        ToolUtils.saveLoginInfo(getActivity(), loginBean.getUsername());
        getActivity().finish();
    }

    public void doLoginError(String msg) {
        mCurrentActivity.finish();
    }

    @Override
    protected void dataObserver() {
        mViewModel.mDoLogin.observe(this, this::doLoginSuccess);
        mViewModel.mDoLoginError.observe(this, this::doLoginError);
    }
}
